<template>
  <div class="container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>编辑学生信息</span>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>
      
      <el-form ref="formRef" :model="student" :rules="rules" label-width="120px" style="max-width: 600px;">
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="student.studentId" disabled />
        </el-form-item>
        
        <el-form-item label="学生姓名" prop="name">
          <el-input v-model="student.name" placeholder="请输入学生姓名" />
        </el-form-item>
        
        <el-form-item label="宿舍楼" prop="dormBuildId">
          <el-select 
            v-model="student.dormBuildId" 
            placeholder="请选择宿舍楼"
            style="width: 100%"
            @change="handleDormChange"
          >
            <el-option
              v-for="dorm in dorms"
              :key="dorm.dormBuildId"
              :label="dorm.dormBuildName"
              :value="dorm.dormBuildId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="student.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  data() {
    return {
      student: {
        studentId: null,
        name: '',
        dormBuildId: null,
        dormName: '',
        sex: '男'
      },
      dorms: [],
      rules: {
        name: [
          { required: true, message: '请输入学生姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        dormBuildId: [
          { required: true, message: '请选择宿舍楼', trigger: 'change' }
        ],
        dormName: [
          { required: true, message: '请输入宿舍号', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ]
      }
    }
  },
  async created() {
    await this.fetchDorms()
    await this.fetchStudent()
  },
  methods: {
    async fetchStudent() {
      try {
        const studentId = this.$route.params.id
        const response = await axios.get(
          `http://localhost:8080/UserMgr_Web_exploded/students/${studentId}`,
          {
            headers: {
              'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
          }
        )
        // 将后端返回的数据映射到前端表单结构
        const backendData = response.data
        this.student = {
          studentId: backendData.studentId,
          name: backendData.name,
          dormBuildId: this.getDormBuildIdByName(backendData.dormBuildName),
          dormName: backendData.dormName,
          sex: backendData.sex
        }
      } catch (error) {
        ElMessage.error('获取学生信息失败')
        console.error(error)
      }
    },
    async fetchDorms() {
      try {
        const response = await axios.get(
          "http://localhost:8080/UserMgr_Web_exploded/dorms",
          {
            headers: {
              'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
          }
        )
        this.dorms = response.data
      } catch (error) {
        ElMessage.error('获取宿舍楼列表失败')
        console.error(error)
      }
    },
    // 根据宿舍楼名称查找对应的ID
    getDormBuildIdByName(dormBuildName) {
      if (!dormBuildName || !this.dorms.length) return null
      const found = this.dorms.find(dorm => dorm.dormBuildName === dormBuildName)
      return found ? found.dormBuildId : null
    },
    handleDormChange(value) {
      // 当宿舍楼改变时，可以在这里添加额外逻辑
      console.log('选择的宿舍楼ID:', value)
    },
    async submitForm() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            // 准备发送给后端的数据
            const submitData = {
              studentId: this.student.studentId,
              name: this.student.name,
              dormBuildName: this.getDormBuildNameById(this.student.dormBuildId),
              dormName: this.student.dormName,
              sex: this.student.sex
            }
            
            const response = await axios.put(
              `http://localhost:8080/UserMgr_Web_exploded/students/${this.student.studentId}`,
              submitData,
              {
                headers: {
                  'Authorization': 'Bearer ' + localStorage.getItem('token')
                }
              }
            )
            
            if (response.data.success) {
              ElMessage.success('更新学生信息成功')
              this.$router.push('/students')
            } else {
              ElMessage.error(response.data.message || '更新失败')
            }
          } catch (error) {
            ElMessage.error('更新学生信息失败')
            console.error(error)
          }
        }
      })
    },
    // 根据宿舍楼ID查找对应的名称
    getDormBuildNameById(dormBuildId) {
      if (!dormBuildId || !this.dorms.length) return ''
      const found = this.dorms.find(dorm => dorm.dormBuildId === dormBuildId)
      return found ? found.dormBuildName : ''
    },
    resetForm() {
      this.fetchStudent() // 重新获取原始数据
    },
    goBack() {
      this.$router.push('/students')
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>